//
//  VRFirefightingDeviceViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/17.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRFirefightingDeviceViewController.h"

#import "VRFirefightingDeviceModel.h"
#import "VRFirefightingDeviceCell.h"
#import "XNicknameAlertView.h"

@interface VRFirefightingDeviceViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *searchBlankView;
@property (nonatomic, strong) UILabel *searchlab;

@property (nonatomic, strong) NSMutableArray<VRFirefightingDeviceModel *> *modelArray;
@property (nonatomic, strong) NSMutableArray<VRFirefightingDeviceModel *> *searchResArray;

@property (nonatomic, strong) XNicknameAlertView *editAlertView;

@property (nonatomic, assign) NSInteger curSelectedIndex;

@property (nonatomic, assign) BOOL isSearched;

@end

@implementation VRFirefightingDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"消防设备设置";
    
    self.modelArray = [NSMutableArray array];
    self.searchResArray = [NSMutableArray array];
    
    [self setupSubView];
    
//    weakify(self)
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        strongify(self)
//        [self getContact];
//    }];
    
    [self getDeviceList];
}

- (void)setupSubView
{
    
    
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = RGB(220, 220, 220);
    headerView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 40);
    [self.view addSubview:headerView];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.layer.cornerRadius = 8;
    NSArray *subViews;
    subViews = [(searchBar.subviews[0]) subviews];
    for (id view in subViews)
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            UIButton* cancelbutton = (UIButton* )view;
            [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
            break;
        }
    }
    
    searchBar.tintColor = [UIColor grayColor];
    searchBar.frame = CGRectMake(0, 0, kScreenWidth, 44);
    [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex : 0] removeFromSuperview];
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.searchBar = searchBar;
//
//    UISearchBar *searchBar = [[UISearchBar alloc] init];
//    searchBar.placeholder = @"输入关键字搜索";
//    searchBar.showsCancelButton = YES;
    searchBar.frame = CGRectMake(0, 3, kScreenWidth, 34);
    [headerView addSubview:searchBar];
}

- (void)filterContentForSearchText:(NSString *)searchText
{
    
    if (searchText.length > 0) {
        
        NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
        
        [self.searchResArray removeAllObjects];
        for (int i = 0; i < self.modelArray.count; i++) {
            
            VRFirefightingDeviceModel *model = self.modelArray[i];
            NSRange nameRange = [model.fTypeName rangeOfString:searchText options:searchOptions];
            NSRange typeRange = [model.fFacilityModelID rangeOfString:searchText options:searchOptions];
            NSRange noteRange = [model.fAlias rangeOfString:searchText options:searchOptions];
            
            if (nameRange.length || typeRange.length || noteRange.length){
                
                [self.searchResArray addObject:model];
            }
            
        }
    }
    
    if (self.searchResArray.count == 0) {
        
        self.searchBlankView.hidden  = NO;
        NSMutableAttributedString *mutAttriString  = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"没有找到“%@”相关结果",self.searchBar.text]];
        [mutAttriString addAttribute:NSForegroundColorAttributeName value:RGB(153, 202, 247) range:NSMakeRange(5, mutAttriString.length -10)];
        
        self.searchlab.attributedText = mutAttriString;
    }else{
         self.searchBlankView.hidden  = YES;
        if (_searchBlankView) {
            self.searchBlankView.hidden  = YES;
//            [[_searchBlankView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
//            self.searchBlankView = nil;
        }
    }
}


#pragma mark - networking
- (void)getDeviceList
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:MyDeviceInfo parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.modelArray = [VRFirefightingDeviceModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}

- (void)updateMyInfoWith:(NSString *)note isOn:(NSNumber *)isOn
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"fID"] = self.modelArray[self.curSelectedIndex].fID;
    if (note) {
        if (note.length > 0) {
            param[@"remark"] = note;
        }else{
            param[@"remark"] = @" ";
        }
    }else{
        if (self.searchResArray.count > 0) {
            param[@"remark"] = self.searchResArray[self.curSelectedIndex].fAlias.length > 0 ? self.searchResArray[self.curSelectedIndex].fAlias : @" ";
        }else{
            param[@"remark"] = self.modelArray[self.curSelectedIndex].fAlias.length > 0 ? self.modelArray[self.curSelectedIndex].fAlias : @" ";
        }
    }
    if (isOn) {
        param[@"state"] = isOn.boolValue ? @(0) : @(1);
    }else{
        if (self.searchResArray.count > 0) {
            param[@"state"] = @(!self.searchResArray[self.curSelectedIndex].fType);
        }else{
            param[@"state"] = @(!self.modelArray[self.curSelectedIndex].fType);
        }
    }
    
//    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:UpdateDeviceInfo parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.editAlertView dissmiss];
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                
                VRFirefightingDeviceModel *model = nil;
                if (self.searchResArray.count > 0) {
                    model = self.searchResArray[self.curSelectedIndex];
                }else{
                    model = self.modelArray[self.curSelectedIndex];
                }
                if (isOn) {
                    model.fFacilitySwitch = isOn.boolValue ? 0 : 1;
                }
                if (note) {
                    model.fAlias = note;
                }
                
                [self.tableView reloadData];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


#pragma mark - action
- (void)onHistoryBtnClick:(UIButton *)sender
{
    
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSearched) {
        return self.searchResArray.count;
    }
    return self.modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 140;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VRFirefightingDeviceModel *model = nil;
    if (self.isSearched) {
        model = self.searchResArray[indexPath.row];
    }else{
        model = self.modelArray[indexPath.row];
    }
    
    VRFirefightingDeviceCell *cell = [VRFirefightingDeviceCell cellWith:tableView];
    cell.model = model;
    weakify(self)
    cell.editClickBlock = ^{
        
        strongify(self)
        self.curSelectedIndex = indexPath.row;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.editAlertView.text = model.fAlias;
            [self.editAlertView show];
        });
    };
    cell.swithClickBlock = ^(BOOL isOpen) {
        
        strongify(self)
        self.curSelectedIndex = indexPath.row;
        [self updateMyInfoWith:nil isOn:[NSNumber numberWithBool:isOpen]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma  mark searchController delgate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;{
    //    NSString *filterString = searchController.searchBar.text;
    //
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", filterString];
    //    self.searchArry = [NSMutableArray arrayWithArray:[self.tableArry filteredArrayUsingPredicate:predicate]];
    //    //    UITableViewController *searchTableController=(UITableViewController *)searchController;
    //    [self.searchResultsController.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController
{
    self.tabBarController.tabBar.hidden = YES;
}


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //    self.tabBarController.tabBar.hidden = YES;
    //    self.navigationController.navigationBar.hidden = YES;
    
    
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //取消
    [searchBar resignFirstResponder];
    
    self.isSearched = NO;
    searchBar.text = nil;
    //
    self.searchBlankView.hidden  = YES;
    [self.tableView reloadData];
}


- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
//    self.isSearched = NO;
//    searchBar.text = nil;
    [searchBar setShowsCancelButton:NO animated:YES];
//
//    if (_searchBlankView) {
//        self.searchBlankView.hidden  = YES;
//        [[_searchBlankView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
//        self.searchBlankView = nil;
//    }
//    
//    [self.tableView reloadData];
    return YES;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if (searchBar.text.length == 0) {
        [searchBar resignFirstResponder];
        [searchBar setShowsCancelButton:NO animated:YES];
        self.isSearched = NO;
        
        self.searchBlankView.hidden  = YES;
        [self.tableView reloadData];
    }else{
        
        self.isSearched = YES;
        
        //        [self getSearchResultBy:searchBar.text];
        [self filterContentForSearchText:searchBar.text];
        
        [self.tableView reloadData];
    }
    
}

#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 40, kScreenWidth, kScreenHeight - NAVIGATION_BAR_HEIGHT - 40) style:UITableViewStylePlain];
        _tableView.backgroundColor = ScrollViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [[UIView alloc] init];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];
        _tableView.tableFooterView = view1;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionFooterHeight = 0.01;
        [self.view addSubview:self.tableView];
        //        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.right.bottom.mas_equalTo(self.view);
        //            make.top.mas_equalTo(0);
        //        }];
    }
    return _tableView;
}




- (XNicknameAlertView *)editAlertView
{
    if (_editAlertView == nil) {
        
        _editAlertView = [[XNicknameAlertView alloc] init];
        weakify(self)
        _editAlertView.SaveBlock = ^(NSString *text) {
            
            strongify(self)
            [self updateMyInfoWith:text isOn:nil];
        };
    }
    return _editAlertView;
}

- (UIView *)searchBlankView
{
    if (_searchBlankView == nil) {
        
        UIView *blankView = [UIView new];
        [self.view addSubview:blankView];
        [blankView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.top.mas_equalTo(self.searchBar.mas_bottom);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth, 100));
        }];
        _searchBlankView = blankView;
        
        UILabel *label = [UILabel new];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor lightGrayColor];
        self.searchlab = label;
        NSMutableAttributedString *mutAttriString  = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"没有找到“%@”相关结果",self.searchBar.text]];
        [mutAttriString addAttribute:NSForegroundColorAttributeName value:RGB(153, 202, 247) range:NSMakeRange(5, mutAttriString.length -10)];
        
        
        label.attributedText = mutAttriString;
        [blankView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(blankView.center);
            make.size.mas_equalTo(CGSizeMake(kScreenWidth, 20));
        }];
    }
    return _searchBlankView;
}

@end
